#include <iostream>
#include <string>
#include <memory>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include "socket.hpp"
#include "protocol.hpp"
#include "Log.hpp"
Log lg;
using namespace std;
void Usage(const std::string &cmd)
{
    cout << "\n\r" << cmd << " serverip serverport" << endl
         << endl;
}
int main(int argc, char *argv[])
{
    srand(time(nullptr));
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    string ip = argv[1];
    uint16_t port = stoi(argv[2]);
    Sock sock;
    sock.Socket();
    if(!sock.Connect(ip, port)) return 1;
    int cnt = 1;
    const std::string opers = "+-*/%=-=&^";
    std::string inbuffer_stream;
    while(cnt <= 10)
    {
        std::cout << "===============第" << cnt << "次测试....., " << "===============" << std::endl;
        int x = rand() % 10 + 1;
        usleep(1234);
        int y = rand() % 5;
        char op = opers[rand() % opers.size()];
        Request req(x, y, op);
        string req_str;
        req.Serialize(req_str);
        req_str = EnCode(req_str);

        write(sock.Fd(), req_str.c_str(), req_str.size());
        write(sock.Fd(), req_str.c_str(), req_str.size());
        write(sock.Fd(), req_str.c_str(), req_str.size());
        write(sock.Fd(), req_str.c_str(), req_str.size());

        char buffer[1280];
        int n = read(sock.Fd(), buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;
            string resp_str;
            bool r = DeCode(inbuffer_stream, resp_str);
            assert(r);
            Response resp;
            r = resp.DeSerialize(resp_str);
            assert(r);
            
            resp.DebugPrint();
            std::cout << "=================================================" << std::endl;
            sleep(1);

            cnt++;
        }
        else break;
    }
    sock.Close();
    return 0;
}